from PyQt5.Qt import QCursor
from PyQt5.QtWidgets import QMainWindow,QShortcut
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter,QKeySequence,QColor,QPen

class SelectArea(QMainWindow):
    left,right,top,bottom = 0,0,0,0
    control_area = None
    rect = None

    def __init__(self, control_area):
        super().__init__()
        # 取消原生标题栏 | 窗口置顶 | 取消任务栏
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
        # 窗口全屏
        self.showFullScreen()
        self.control_area = control_area
        # 设置背景色
        self.setObjectName("Selectrect_area")
        self.setStyleSheet("#Selectrect_area{background-color:black}")
        # 设置透明度
        self.setWindowOpacity(0.3)
        # 注册热键
        QShortcut(QKeySequence(self.tr("ESC")), self, self.close)
        # 设置鼠标样式
        self.setCursor(Qt.CrossCursor)
        
    # 重写绘制函数
    def paintEvent(self,event):
        # 初始化绘图工具
        qp = QPainter()
        # 开始在窗口绘制
        qp.begin(self)
        #自定义画点方法
        if self.rect:
            self.drawRect(qp)
        # 结束在窗口的绘制
        qp.end()

    def drawRect(self,qp):
        # 创建天蓝色，宽度为2像素的画笔
        pen = QPen(QColor('#66ccff'), 2)
        qp.setPen(pen)
        qp.drawRect(*self.rect)

    def mousePressEvent(self, event):
        # 法一
        # pos = QCursor.pos()
        # self.top = pos.y()
        # self.left = pos.x()
        # 法二
        self.top = event.globalY()
        self.left = event.globalX()
        print(self.left, self.top)
        self.rect = (self.left, self.top, 0, 0)
        
    def mouseReleaseEvent(self, event):
        pos = QCursor.pos()
        self.bottom = pos.y()
        self.right = pos.x()
        print(self.right, self.bottom)
        if self.top > self.bottom:
            self.top, self.bottom = self.bottom, self.top
        if self.left > self.right:
            self.left, self.right = self.right, self.left
        self.control_area.changeArea((self.left, self.top), (self.right-self.left, self.bottom-self.top))
        self.close()

    # 鼠标移动时更新矩形
    def mouseMoveEvent(self, event):
        start_x, start_y = self.rect[0:2]
        self.rect = (start_x, start_y, event.x() - start_x, event.y() - start_y)
        # 触发绘制事件
        self.update()